package com.github.live.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;


import com.github.livebase.util.base.ObjectsUtil;

import java.util.List;

public abstract class SimpleRecyclerAdapter<T> extends RecyclerView.Adapter<SimpleViewHolder> {
    private int resId;
    private List<T> mData;
    protected Context mContext;

    public SimpleRecyclerAdapter(@IdRes int resId, List<T> mData) {
        this.resId = resId;
        this.mData = mData;
    }
    public SimpleRecyclerAdapter(@IdRes int resId) {
        this(resId, ObjectsUtil.Empty.LIST);
    }

    @NonNull
    @Override
    public SimpleViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        this.mContext = parent.getContext();
        View view = LayoutInflater.from(mContext).inflate(resId, parent, false);
        return new SimpleViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull SimpleViewHolder holder, int position) {
        onBindViewHolder(holder, mData.get(position), position);
    }
    abstract void onBindViewHolder(SimpleViewHolder holder, T data, int position);

    @Override
    public int getItemCount() {
        return mData == null ? 0 : mData.size();
    }

    public void setData(List<T> mData) {
        if (ObjectsUtil.safeEquals(this.mData, mData)) {
            return;
        }
        this.mData = mData;
        notifyDataSetChanged();
    }

    public T getItem(int index) {
        if (index < 0 || index >= this.mData.size()) {
            return null;
        }
        return this.mData.get(index);
    }
}